package com.aioething.iot.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aioething.iot.dao.FirmwareDao;
import com.aioething.iot.dao.OtaTaskDao;
import com.aioething.iot.dto.OtaTaskDto;
import com.aioething.iot.model.Firmware;
import com.aioething.iot.model.OtaTask;
import com.aioething.iot.service.IEmqxService;
import com.aioething.iot.service.IOtaTaskService;
import com.aioething.iot.vo.OtaTaskVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Service
public class OtaTaskService implements IOtaTaskService {
    @Autowired
    private OtaTaskDao otaTaskDao;
    @Autowired
    private FirmwareDao firmwareDao;
    @Autowired
    private IEmqxService emqxService;

    @Override
    public PageInfo<OtaTaskVo> query(OtaTaskDto otaTaskDto) {
        PageHelper.startPage(otaTaskDto.getPageNo(), otaTaskDto.getPageSize());
        List<OtaTaskVo> list = otaTaskDao.query(otaTaskDto);
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public void create(OtaTask otaTask) throws IOException {
        // 查询固件信息
        Firmware firmware = firmwareDao.selectByPrimaryKey(otaTask.getFirmwareId());
        if (ObjectUtil.isNull(firmware))
            throw new InternalException("固件不存在");
        otaTask.setVersion(firmware.getVersion());
        otaTaskDao.insertSelective(otaTask);
        // 发送指令
        JSONObject params = JSONUtil.createObj()
                .set("taskId", otaTask.getTaskId())
                .set("version", firmware.getVersion())
                .set("url", firmware.getUrl())
                .set("size", firmware.getSize())
                .set("md5", firmware.getMd5());
        JSONObject obj = emqxService.actionCall(String.format("things/%s/%s/ota/down", otaTask.getEquipmentId().split("/")[0], otaTask.getEquipmentId().split("/")[1]),"ota", otaTask.getEquipmentId(), params);
        Integer code = obj.getInt("code", -1);
        if (code != 0) {
            throw new InternalException(String.format("OTA失败(%d)", code));
        }
    }

    @Override
    public int delete(String taskId) {
        return otaTaskDao.deleteByPrimaryKey(taskId);
    }
}
